package com.rem.web;

import com.rem.pojo.Book;
import com.rem.pojo.Page;
import com.rem.service.BookService;
import com.rem.service.impl.BookServiceImpl;
import com.rem.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

public class ClientBookServlet extends BaseServlet{
    BookService bookService = new BookServiceImpl();

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("this method is invoked...");
        Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Book> page = bookService.page(pageNo, pageSize);
        page.setUrl("client/bookServlet?action=page");
        req.setAttribute("page",page);
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }

    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("this method is invoked...");

        Integer pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        Integer minPrice = WebUtils.parseInt(req.getParameter("min"),0);
        Integer maxPrice = WebUtils.parseInt(req.getParameter("max"),Integer.MAX_VALUE);

        if (minPrice > maxPrice) {
            maxPrice = minPrice;
        }

        Page<Book> page = bookService.pageByPrice(pageNo, pageSize, minPrice, maxPrice);
        StringBuilder sb = new StringBuilder();

        sb.append("client/bookServlet?action=pageByPrice");

        if (!Objects.isNull(req.getParameter("min")) ){
            sb.append("&min="+req.getParameter("min"));
        }
        if (!Objects.isNull(req.getParameter("max"))){
           sb.append("&max="+req.getParameter("max"));
        }
        
        page.setUrl(sb.toString());

        req.setAttribute("page",page);
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }
}
